package com.orion.smart.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author <a href="http://github.com/athc">dujf</a>
 * @date 2018/9/10
 * @since JDK1.8
 */
@RestController
@RequestMapping("/redis/hash")
public class RedisHashController {

  private final RedisTemplate redisTemplate;

  @Autowired public RedisHashController(RedisTemplate redisTemplate) {this.redisTemplate = redisTemplate;}

  /**
   * 添加
   */
  @PostMapping
  public void setString() {
    //单个添加
    redisTemplate.opsForHash().put("user:2", "name", "lisi");
    redisTemplate.opsForHash().put("user:2", "amount", 99);
    //给指定value添加值
//    redisTemplate.opsForHash().increment("user:2", "amount", 1.0);
    //多个添加
    Map map = new HashMap<>();
    map.put("name", "zhang");
    map.put("amount", 100);
    redisTemplate.opsForHash().putAll("user:1", map);
  }

  /**
   * 查询
   */
  @GetMapping
  public void getString() {
    Object result = null;
    //查询单个key 对应value
    result = redisTemplate.opsForHash().get("user:1", "name");
    logger.info(String.valueOf(result));

    //查询整个hash
    result = redisTemplate.opsForHash().entries("user:2");
    logger.info(String.valueOf(result));

    //获取整个hash 转为list
    List<String> list = new ArrayList<>();
    list.add("name");
    list.add("amount");
    //传入hashkey集合取出value
    result = redisTemplate.opsForHash().multiGet("user:1", list);
    logger.info(String.valueOf(result));

    //判断hash key是否存在
    result = redisTemplate.opsForHash().hasKey("user:1", "name");
    logger.info(String.valueOf(result));

  }

  /**
   * 删除
   */
  @DeleteMapping
  public void deleteString() {
    Object result = redisTemplate.opsForHash().delete("user:1", "name");
    logger.info(String.valueOf(result));
  }

  private Logger logger = LoggerFactory.getLogger(RedisHashController.class);
}
